<template>
  <el-container>
    <!-- 侧边栏 -->
    <el-aside class="home-aside" width="250px">
      <!-- logo -->
      <div class="home-logo-div">
        <router-link to="/owner/home">
          <el-image
            class="home-logo"
            src="../src/assets/logo_trans.png"
            fit="contain"
          ></el-image
        ></router-link>
      </div>
      <!-- 折叠icon -->
      <el-icon
        class="toggle-button"
        v-model="isCollapse"
        @click="toggleCollapse"
        size="20px"
      >
        <Fold v-if="!isCollapse" />
        <Expand v-if="isCollapse" />
      </el-icon>
      <!-- 侧边栏菜单 -->
      <el-menu
        class="home-menu-vertical"
        :collapse="isCollapse"
        :default-active="$route.path"
        router
      >
        <el-menu-item index="/owner/food">
          <el-icon>
            <Edit />
          </el-icon>
          <span slot="title">菜品管理</span>
        </el-menu-item>
        <el-menu-item index="/owner/order">
          <el-icon>
            <Bell />
          </el-icon>
          <span slot="title">订单管理</span>
        </el-menu-item>
        <el-menu-item index="/owner/account">
          <el-icon>
            <User />
          </el-icon>
          <span slot="title">我的账号</span>
        </el-menu-item>
      </el-menu>
      <el-image src="../src/assets/plate.png" class="plate-div"></el-image>
    </el-aside>

    <el-container>
      <!-- 头部 -->
      <el-header class="food-header" height="40px">
        <div class="ball"></div>
        <div class="food-line"></div>
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/owner/home' }"> 主页 </el-breadcrumb-item>
          <el-breadcrumb-item>菜品列表</el-breadcrumb-item>
        </el-breadcrumb>
      </el-header>

      <!-- 主体 -->
      <el-main class="home-main">
        <!-- 食品列表 -->
        <el-table
          :data="filterTableData"
          style="width: 100%"
          :default-sort="{ prop: 'foodName', order: 'descending' }"
          v-loading="loading"
          height="540"
        >
          <el-table-column type="index" width="50" />
          <el-table-column prop="photo" label="图片" width="120"
            ><template #default="scope">
              <el-image
                class="food-o-image"
                :src="scope.row.photo"
                fit="cover"
                @click="gotoFoodDetail(scope.row.id)"
              ></el-image>
            </template>
          </el-table-column>
          <el-table-column prop="foodName" label="名称" width="150" />
          <el-table-column prop="price" label="价格" sortable width="80" />
          <el-table-column
            prop="label"
            label="类别"
            width="120"
            :filters="[
              { value: '氧气创意披萨', text: '氧气创意披萨' },
              { value: '氧气芝士焗饭', text: '氧气芝士焗饭' },
              { value: '氧气元气轻食', text: '氧气元气轻食' },
              { value: '氧气嗨嗨小吃', text: '氧气嗨嗨小吃' },
              { value: '氧气超爽饮品', text: '氧气超爽饮品' },
            ]"
            :filter-method="filterTag"
            ><template #default="scope">
              <el-tag disable-transitions>{{ scope.row.label }}</el-tag>
            </template></el-table-column
          >
          <el-table-column prop="saleNumber" label="销量" width="80" sortable />
          <el-table-column prop="foodScore" label="评分" sortable width="200"
            ><template #default="scope">
              <!-- 在插槽中放置评分组件 -->
              <el-rate
                v-model="scope.row.foodScore"
                disabled
                show-score
                text-color="#ff9900"
                :score-template="'{value} points'"
                size="small"
              ></el-rate> </template
          ></el-table-column>
          <!-- 自定义列 -->
          <el-table-column align="right" width="300">
            <template #header>
              <el-input
                v-model="search"
                size="small"
                placeholder="搜索菜品"
                style="width: 150px; margin-right: 10px"
              />
              <el-button
                color="#E3A566"
                class="food-o-add-button"
                size="small"
                @click="openAddDialog"
                >添加菜品</el-button
              >
            </template>
            <template #default="scope">
              <el-button type="warning" size="small" @click="gotoFoodDetail(scope.row.id)"
                >查看</el-button
              >
              <el-button
                type="info"
                size="small"
                @click="handleEdit(scope.$index, scope.row)"
                >编辑</el-button
              >
              <el-button
                size="small"
                type="danger"
                @click="handleDelete(scope.$index, scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
          <el-pagination
            background
            :current-page="pagination.currentPage"
            :page-size="pagination.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.totalCount"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          >
          </el-pagination>
        </div>
      </el-main>
      <!-- 回到顶部 -->
      <el-backtop :right="80" :bottom="100" />
    </el-container>
  </el-container>
  <!-- 添加菜品 -->
  <el-dialog
    v-model="isAddDialogShow"
    title="添加菜品"
    width="700px"
    class="food-o-dialog"
  >
    <el-form :model="addFoodForm" class="food-o-add-form">
      <el-form-item label="图片">
        <el-upload
          class="avatar-uploader"
          action="http://localhost:8080/photo/upload/food"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <el-image v-if="addphoto" :src="addphoto" class="avatar" fit="cover" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="名称">
        <el-input v-model="addFoodForm.foodName" autocomplete="off" />
      </el-form-item>
      <el-form-item label="价格">
        <el-input-number v-model="addFoodForm.price" :min="0" />
      </el-form-item>
      <el-form-item label="类别">
        <el-select v-model="addFoodForm.label" clearable placeholder="类别">
          <el-option
            v-for="item in labelOptions"
            :key="item.value"
            :label="item.label"
            :value="item.label"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <el-form :model="addFoodForm" class="food-o-add-form" :inline="true">
      <el-form-item label="辣" prop="spicy">
        <el-rate
          v-model="addFoodForm.foodFlavor.spicy"
          void-icon="ChatRound"
          :colors="['#409eff', '#67c23a', '#FF9900']"
        />
      </el-form-item>
      <el-form-item label="甜" prop="sweet">
        <el-rate
          v-model="addFoodForm.foodFlavor.sweet"
          void-icon="ChatRound"
          :colors="['#409eff', '#67c23a', '#FF9900']"
        />
      </el-form-item>
      <el-form-item label="咸" prop="salted">
        <el-rate
          v-model="addFoodForm.foodFlavor.salted"
          void-icon="ChatRound"
          :colors="['#409eff', '#67c23a', '#FF9900']"
        />
      </el-form-item>
      <el-form-item label="酸" prop="acid">
        <el-rate
          v-model="addFoodForm.foodFlavor.acid"
          void-icon="ChatRound"
          :colors="['#409eff', '#67c23a', '#FF9900']"
        />
      </el-form-item>
      <el-form-item label="重口" prop="heavyTaste">
        <el-rate
          v-model="addFoodForm.foodFlavor.heavyTaste"
          void-icon="ChatRound"
          :colors="['#409eff', '#67c23a', '#FF9900']"
        />
      </el-form-item>
      <el-form-item label="热" prop="hotLevel">
        <el-rate
          v-model="addFoodForm.foodFlavor.hotLevel"
          void-icon="ChatRound"
          :colors="['#409eff', '#67c23a', '#FF9900']"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button class="loginBtn" round color="#E3A566" @click="addFood">确认</el-button>
    </template>
  </el-dialog>
  <!-- 编辑菜品 -->
  <el-dialog
    v-model="isEditDialogShow"
    title="编辑菜品"
    width="700px"
    class="food-o-dialog"
  >
    <el-form :model="editFoodForm" class="food-o-add-form">
      <el-form-item label="图片">
        <el-upload
          class="avatar-uploader"
          action="http://localhost:8080/photo/upload/food"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <el-image v-if="addphoto" :src="addphoto" class="avatar" fit="cover" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="名称">
        <el-input v-model="editFoodForm.foodName" autocomplete="off" />
      </el-form-item>
      <el-form-item label="价格">
        <el-input-number v-model="editFoodForm.price" :min="0" />
      </el-form-item>
      <el-form-item label="类别">
        <el-select v-model="editFoodForm.label" clearable placeholder="类别">
          <el-option
            v-for="item in labelOptions"
            :key="item.value"
            :label="item.label"
            :value="item.label"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <el-form :model="editFoodForm" class="food-o-add-form" :inline="true">
      <el-form-item label="辣" prop="spicy">
        <el-rate
          v-model="editFoodForm.foodFlavor.spicy"
          void-icon="ChatRound"
          :colors="['#409eff', '#67c23a', '#FF9900']"
        />
      </el-form-item>
      <el-form-item label="甜" prop="sweet">
        <el-rate
          v-model="editFoodForm.foodFlavor.sweet"
          void-icon="ChatRound"
          :colors="['#409eff', '#67c23a', '#FF9900']"
        />
      </el-form-item>
      <el-form-item label="咸" prop="salted">
        <el-rate
          v-model="editFoodForm.foodFlavor.salted"
          void-icon="ChatRound"
          :colors="['#409eff', '#67c23a', '#FF9900']"
        />
      </el-form-item>
      <el-form-item label="酸" prop="acid">
        <el-rate
          v-model="editFoodForm.foodFlavor.acid"
          void-icon="ChatRound"
          :colors="['#409eff', '#67c23a', '#FF9900']"
        />
      </el-form-item>
      <el-form-item label="重口" prop="heavyTaste">
        <el-rate
          v-model="editFoodForm.foodFlavor.heavyTaste"
          void-icon="ChatRound"
          :colors="['#409eff', '#67c23a', '#FF9900']"
        />
      </el-form-item>
      <el-form-item label="热" prop="hotLevel">
        <el-rate
          v-model="editFoodForm.foodFlavor.hotLevel"
          void-icon="ChatRound"
          :colors="['#409eff', '#67c23a', '#FF9900']"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <!-- <span class="dialog-footer"> -->
      <el-button class="loginBtn" round color="#E3A566" @click="editFood">确认</el-button>
      <!-- </span> -->
    </template>
  </el-dialog>
</template>

<script>
import { mapState } from "vuex";
import { ElMessageBox, ElMessage } from "element-plus";

export default {
  data() {
    return {
      isCollapse: false, //是否折叠侧边栏
      search: "",
      tableData: [],
      addFoodForm: {
        id: "",
        photo: "",
        foodName: "",
        price: "",
        label: "",
        foodFlavor: {
          spicy: "",
          sweet: "",
          salted: "",
          acid: "",
          heavyTaste: "",
          hotLevel: "",
        },
      },
      addphoto: "",
      editFoodForm: {
        id: "",
        photo: "",
        foodName: "",
        price: "",
        label: "",
        foodFlavor: {
          spicy: "",
          sweet: "",
          salted: "",
          acid: "",
          heavyTaste: "",
          hotLevel: "",
        },
      },
      isAddDialogShow: false,
      isEditDialogShow: false,
      labelOptions: [
        {
          value: "Option1",
          label: "氧气创意披萨",
        },
        {
          value: "Option2",
          label: "氧气芝士焗饭",
        },
        {
          value: "Option3",
          label: "氧气元气轻食",
        },
        {
          value: "Option4",
          label: "氧气嗨嗨小吃",
        },
        {
          value: "Option5",
          label: "氧气超爽饮品",
        },
      ],
      pagination: {
        currentPage: 1, // 起始页
        pageSize: 10, // 每页的数据
        totalCount: 0, // 总数据
      },
      loading: false,
    };
  },
  computed: {
    filterTableData() {
      let _this = this;
      return _this.tableData.filter((data) => {
        return (
          !_this.search ||
          data.foodName.toLowerCase().includes(_this.search.toLowerCase())
        );
      });
    },
  },
  created() {
    this.getFood(this.pagination.currentPage, this.pagination.pageSize);
  },
  methods: {
    // 切换侧边栏的折叠与展开
    toggleCollapse() {
      this.isCollapse = !this.isCollapse;
    },
    getFood(currentPage, pageSize) {
      this.loading = true;
      let url = "/foods" + "?pageNum=" + currentPage + "&&pageSize=" + pageSize;
      let _this = this;
      _this.$http.get(url).then(function (response) {
        _this.tableData = response.data.records;
        //获取照片url
        for (let i = 0; i < response.data.records.length; i++) {
          _this.tableData[i].photo = "http://localhost:8080" + _this.tableData[i].photo;
        }
        console.log(_this.tableData);
        // 更新分页控件的显示数据
        _this.pagination.currentPage = response.data.current;
        _this.pagination.pageSize = response.data.size;
        _this.pagination.totalCount = parseInt(response.data.total);
        _this.loading = false;
      });
    },
    // 查看菜品详情
    gotoFoodDetail(id) {
      //去食物详情页面
      this.$router.push({
        path: "/owner/fooddetail",
        state: {
          foodID: id,
          lastpage: "/owner/food",
        },
      });
    },
    // 筛选类别
    filterTag(value, row) {
      console.log("row.label = ", row.label);
      console.log("value = ", value);
      return row.label === value;
    },
    openAddDialog() {
      this.isAddDialogShow = true;
    },
    // 添加菜品
    addFood() {
      let _this = this;
      let url = "/foods";
      console.log(this.addFoodForm.photo);
      this.$http
        .post(url, this.addFoodForm)
        .then(function (response) {
          //成功插入后，将信息更新到表格中
          console.log(response.data);
          _this.addFoodForm.id = response.data.id;
          _this.addFoodForm.photo = "http://localhost:8080" + response.data.photo;
          _this.tableData.push(_this.addFoodForm);
          ElMessage.success("成功添加菜品");
          _this.isAddDialogShow = false;
        })
        .catch(function (error) {
          ElMessage.error("添加菜品失败，请重试!");
        });
    },
    // 上传成功后的处理函数
    handleAvatarSuccess(response, uploadFile) {
      // 将图片地址存储到表单中
      this.addFoodForm.photo = response;
      this.editFoodForm.photo = response;
      this.addphoto = "http://localhost:8080" + response;
      // this.addFoodForm.photo = URL.createObjectURL(uploadFile.raw);
      console.log(this.addFoodForm.photo);
      console.log(this.addphoto);
    },
    // 上传前的检查函数
    beforeAvatarUpload(rawFile) {
      if (rawFile.type !== "image/jpeg") {
        ElMessage.error("Avatar picture must be JPG format!");
        return false;
      } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error("Avatar picture size can not exceed 2MB!");
        return false;
      }
      return true;
    },
    handleEdit(index, row) {
      // index指行索引，row指行对应的实体
      console.log(index, row);
      this.isEditDialogShow = true;
      //设置食品的id
      // this.editFoodForm=row
      var tmp = JSON.parse(JSON.stringify(row));
      tmp.foodFlavor = {};
      this.editFoodForm = tmp;
      this.addphoto = row.photo;
      // this.editFoodForm.photo=this.editFoodForm.photo.replace("http://localhost:8080","");
      let url = "/foodflavor/id/" + row.id;
      let _this = this;
      this.$http.get(url).then(function (response) {
        console.log(response.data);
        _this.editFoodForm.foodFlavor = response.data;
        console.log(_this.editFoodForm);
      });
    },
    // 编辑菜品
    editFood() {
      let _this = this;
      let url = "/foods";
      this.editFoodForm.photo = this.editFoodForm.photo.replace(
        "http://localhost:8080",
        ""
      );
      console.log(this.addphoto);
      console.log("更新的菜品信息为", this.editFoodForm);
      this.$http
        .put(url, this.editFoodForm)
        .then(function (response) {
          //成功插入后，将信息更新到表格中
          _this.editFoodForm.photo = "http://localhost:8080" + _this.editFoodForm.photo;
          //删除原来的信息
          const index = _this.tableData.findIndex(
            (option) => option.id === _this.editFoodForm.id
          );
          _this.tableData.splice(index, 1);
          //将新信息插入
          _this.tableData.push(_this.editFoodForm);
          ElMessage.success("成功修改菜品");
          _this.isEditDialogShow = false;
        })
        .catch(function (error) {
          ElMessage.error(error.data);
        });
      this.isEditDialogShow = false;
    },
    handleDelete(index, row) {
      console.log(index, row);
      ElMessageBox.confirm("", "确定要删除该菜品吗", {
        confirmButtonText: "确认删除",
        cancelButtonText: "我再想想",
      })
        .then(() => {
          // 确认按钮被点击时执行的操作
          let url = "/foods/" + row.id;
          let _this = this;
          this.$http.delete(url).then(function (response) {
            ElMessage({
              type: "success",
              message: "已删除",
            });
            url="/like"
            _this.$http.post(url).then(function (response){
              console.log("更新协同过滤矩阵",response.data)
            })
          });
          //删除这条食品信息
          const index = _this.tableData.findIndex((option) => option.id === row.id);
          _this.tableData.splice(index, 1);
        })
        .catch(() => {
          // 取消按钮被点击时执行的操作
          ElMessage({
            type: "info",
            message: "取消",
          });
        });
    },
    // 改变分页的每页的页数
    handleSizeChange(size) {
      this.getFood(this.pagination.currentPage, size); // 获取数据
    },
    // 改变分页的当前页面
    handleCurrentChange(currentPage) {
      console.log("跳到第", currentPage, " 页");
      this.getFood(currentPage, this.pagination.pageSize); // 获取数据
    },
  },
};
</script>

<style>
.food-o-add-button,
.food-o-add-button:hover,
.food-o-add-button:focus {
  color: white !important;
}

.avatar-uploader .avatar {
  width: 80px;
  height: 70px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 2px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover,
.avatar-uploader .el-upload:focus {
  border-color: #e3a566;
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
}
.food-o-add-form {
  width: 450px;
  margin: 0 auto;
}
.food-o-image {
  width: 100%;
  height: 85px;
  cursor: pointer;
}

.food-o-dialog .el-dialog__body {
  padding: 0px;
}
</style>
